import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../providers/project_provider.dart';
import '../../../domain/entities/project.dart';
import '../../widgets/platform/adaptive_card.dart';
import '../../widgets/platform/responsive_layout.dart';
// 导入窗口管理器
import '../../../core/platform/window_manager.dart';

/// 项目列表页面
class ProjectListPage extends ConsumerStatefulWidget {
  const ProjectListPage({super.key});

  @override
  ConsumerState<ProjectListPage> createState() => _ProjectListPageState();
}

class _ProjectListPageState extends ConsumerState<ProjectListPage> {
  @override
  void initState() {
    super.initState();
    // 加载项目列表
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(projectStateProvider.notifier).loadProjects();
    });

    // 设置窗口为可调整大小
    _setResizableWindow();
  }

  // 设置窗口为可调整大小
  void _setResizableWindow() {
    WindowManager.setWindowStyle(false); // 可调整大小
    // 设置窗口为笔记本大小
    WindowManager.setWindowSize(1200, 800); // 设置窗口大小为更大的笔记本大小
  }

  @override
  Widget build(BuildContext context) {
    final projectState = ref.watch(projectStateProvider);
    final projects = ref.watch(projectsProvider);

    return Scaffold(
      appBar: AppBar(
        title: const SelectableText('项目列表'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () {
              ref.read(projectStateProvider.notifier).loadProjects();
            },
          ),
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              _showCreateProjectDialog(context);
            },
          ),
        ],
      ),
      body: _buildBody(projectState, projects),
    );
  }

  Widget _buildBody(ProjectState state, List<Project> projects) {
    if (state is ProjectLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (state is ProjectError) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.red,
            ),
            const SizedBox(height: 16),
            SelectableText(
              '加载失败',
              style: Theme.of(context).textTheme.headlineSmall,
            ),
            const SizedBox(height: 8),
            SelectableText(
              state.message,
              style: Theme.of(context).textTheme.bodyMedium,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                ref.read(projectStateProvider.notifier).loadProjects();
              },
              child: const SelectableText('重试'),
            ),
          ],
        ),
      );
    }

    if (projects.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.folder_open,
              size: 64,
              color: Colors.grey,
            ),
            const SizedBox(height: 16),
            SelectableText(
              '暂无项目',
              style: Theme.of(context).textTheme.headlineSmall,
            ),
            const SizedBox(height: 8),
            const SelectableText(
              '点击右上角“+”号创建你的第一个项目',
              style: TextStyle(color: Colors.grey),
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              onPressed: () {
                _showCreateProjectDialog(context);
              },
              icon: const Icon(Icons.add),
              label: const SelectableText('创建项目'),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: () async {
        ref.read(projectStateProvider.notifier).loadProjects();
      },
      child: LayoutBuilder(
        builder: (context, constraints) {
          // 使用响应式网格布局
          return _buildResponsiveGrid(projects);
        },
      ),
    );
  }

  Widget _buildResponsiveGrid(List<Project> projects) {
    return ResponsiveGrid(
      spacing: 16,
      runSpacing: 16,
      children: projects.map((project) => _buildProjectCard(project)).toList(),
    );
  }

  Widget _buildProjectCard(Project project) {
    return AdaptiveCard(
      onTap: () {
        context.push('/projects/${project.id}');
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 项目名称和状态
          Row(
            children: [
              Expanded(
                child: Text(
                  project.projectName,
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                ),
              ),
              _buildStatusChip(project.status),
            ],
          ),
          const SizedBox(height: 8),

          // 项目描述
          if (project.description != null)
            Text(
              project.description!,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: Colors.grey[600],
                  ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          const SizedBox(height: 12),

          // 项目信息
          Row(
            children: [
              _buildInfoChip(
                Icons.flag,
                project.priority.description,
                _getPriorityColor(project.priority),
              ),
              const SizedBox(width: 8),
              _buildInfoChip(
                Icons.person,
                project.creatorName,
                Colors.blue,
              ),
              const SizedBox(width: 8),
              if (project.deadline != null)
                _buildInfoChip(
                  Icons.access_time,
                  _formatDate(project.deadline!),
                  Colors.orange,
                ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatusChip(ProjectStatus status) {
    Color color;
    switch (status) {
      case ProjectStatus.planning:
        color = Colors.blue;
        break;
      case ProjectStatus.inProgress:
        color = Colors.green;
        break;
      case ProjectStatus.testing:
        color = Colors.orange;
        break;
      case ProjectStatus.completed:
        color = Colors.purple;
        break;
      case ProjectStatus.cancelled:
        color = Colors.red;
        break;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withValues(alpha: 0.3)),
      ),
      child: SelectableText(
        status.description,
        style: TextStyle(
          color: color,
          fontSize: 12,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  Widget _buildInfoChip(IconData icon, String text, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 14,
            color: color,
          ),
          const SizedBox(width: 4),
          SelectableText(
            text,
            style: TextStyle(
              color: color,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  Color _getPriorityColor(Priority priority) {
    switch (priority) {
      case Priority.high:
        return Colors.red;
      case Priority.medium:
        return Colors.orange;
      case Priority.low:
        return Colors.green;
    }
  }

  String _formatDate(DateTime date) {
    final now = DateTime.now();
    final difference = date.difference(now).inDays;

    if (difference == 0) {
      return '今天';
    } else if (difference == 1) {
      return '明天';
    } else if (difference > 0) {
      return '$difference天后';
    } else {
      return '已过期${difference.abs()}天';
    }
  }

  void _showCreateProjectDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('创建项目'),
        content: const SelectableText('创建项目功能开发中...'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: SelectableText('创建项目功能开发中...')),
              );
            },
            child: const SelectableText('确定'),
          ),
        ],
      ),
    );
  }
}
